<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>购物车</title>
<style>
table{
border-collapse: collapse;
}

thead>tr{
border-bottom:2px solid #B7D1FB ;
}

tbody>tr{
border-bottom:1px solid #B7D1FB; 
}

th,
td{
padding: 12px;
}

a{
text-decoration: none;
}
</style>

</head>
<body>
<table>
<thead>
<tr>
<th>
<input type="checkbox"  id="allab" onclick="SelectAll()"/>
<label for="allcb">全选</label>
</th>
<th>商品</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<!-- 这里空了 -->
<tr>

</tr> 

</table>

<script>
var data=[{

name:'javaScript实战',
price:40,
num:1
},
{
name:'javaScript实战2代',
price:42,
num:2
},
{
name:'javaScript实战3代',
price:43,
num:3
},
];

var tdbody=document.querySelector('table').lastElementChild;
//处理数据
function dealData(){

data.map((x,i)=>Object.assign(x,{id:i,choose:true}))


}dealData();
function init(){

tdbody.innerHTML=`
<tr>
<td id="order" colspan="6" style="text-align: right;">
<span>已经选择16件商品总计</span>
<span style="color: red; font-size: 22px;">731.40</span>
<a href="#" style="border-radius: 4px;
padding:8px;
background:#F08B34;color:#fff">提交订单</a>
</td>
</tr>
`;

data.forEach(o=>appendGood(o));
refreshCash();//刷新金额
}init();

function delGood(i){//删除

data=data.filter(o=>o.id!=i)
init();



}
function plus(i){

data.forEach(o=>o.id==i ? o.num++:'')
init();

}

function minus(i){
data.forEach(o=>o.id==i&&o.num>0 ? o.num--:false)//必须大于0 不能等于0
init();

}
function refreshCash(){
	var td=document.querySelector('#order');
	var newData=data.filter(o=>o.choose);//过滤后的data 接住 再计算总值
	var totalNum=newData.reduce((t,c)=>t+c.num,0);
	var totalPrice=newData.reduce((t,c)=>t+c.num*c.price,0).toFixed(2);
	td.firstElementChild.innerHTML=`已经选择${totalNum}件商品`;
	td.firstElementChild.nextElementSibling.innerHTML=totalPrice;
	
	
}refreshCash();


function appendGood(Obj){
var tr=document.createElement('tr');

var sum=(Obj.num*Obj.price).toFixed(2);//保留2位小数
tr.innerHTML=`
<td>
<input onclick="choose()" type="checkbox" name="c"/>
</td>

<td>${Obj.name}</td>
<td>${Obj.price}</td>

<td>
<button onclick="minus(${Obj.id})">-</button>
<span>${Obj.num}</span>
<button onclick="plus(${Obj.id})">+</button>
</td>

<td style="color: red;">${sum}</td>
<td>
<a href="#" onclick="delGood(${Obj.id})">删除</a>
</td>
`;
tdbody.insertBefore(tr,tdbody.lastElementChild);

};

</script>
</body>
</html>